<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\Admin\SupplierConfiguration;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Support\Facades\DB;


class SupplierDomainMiddleware
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return Application|ResponseFactory|Response|mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $domain = $request->header('supplier-host', $request->host());
        /** @var SupplierConfiguration|null $config **/
        $config = SupplierConfiguration::query()->where(compact('domain'))->first();
        if (!$config) {
            return response('404 not found - ' . $domain, 200);
        }
        $supplier = $config->supplier;
        if (!$supplier) {
            return response('404 not found', 200);
        }
        // 注册db
        $dbKey = $config->registerDbConfig();
        if (!$dbKey) {
            return response('404 not found', 404);
        }
        $request->attributes->set('supplier', $supplier);
        $request->attributes->set('supplier_config', $config);
        $request->attributes->set('supplier_db_connect', $dbKey);
        DB::setDefaultConnection($dbKey);
        // 返回next
        return $next($request);
    }
}
